/*
 * Copyright Eduardo Aponte 2013
 * aponteeduardo@gmail.com
 */
#include <eyelink.h>
#include <string.h>
#include "mex.h"
#include "utils.h"


INT16 _main( UINT32 msec, ELINKADDR node, char FARTYPE *msg )
{
    return eyelink_node_send_message_ex( msec, node, msg );
}

void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    char FARTYPE *msg;
    char FARTYPE *addr;
    ELINKADDR eladdr;
    int i, m;

    /* Verify input arguments. */
    if(nrhs != 3 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 1 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
        
    if ( isscalar( prhs[0] ) ){
        /* Returns the scalar, casts to int if necessary. Returns 0 if */
        /* input is complex. */
        if ( returnscalar( prhs[0], &m ) != 1 )
            mexErrMsgTxt("Complex data is not supported.");                
        if ( m < 0 )
            mexErrMsgTxt("mssec should be positive.");
    } else {
        mexErrMsgTxt("msec should be a scalar."); 
    }
    
    if (!mxIsChar(prhs[1]))
        mexErrMsgTxt("node should be a string.");
       
    if (!mxIsChar(prhs[2]))
        mexErrMsgTxt("msg should be a string.");
     
    addr = mxArrayToString(prhs[1]);

    if ( addr == NULL )
	mexErrMsgTxt("addr could not be read.");
	
    if ( strlen(addr) != ELINKADDRSIZE ){
	mxFree( addr );
	mexErrMsgTxt("node should be a string of len ELINKADDRSIZE (16).");
    }

    msg = mxArrayToString(prhs[2]);
	
    if ( msg == NULL ){
	mxFree( addr );
	mxErrMsgTxt("msg could not be read");
    }
   
    for (i = 0; i < ELINKADDRSIZE; i++)
        eladdr[i] = (byte ) addr[i];
       
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status = mxGetPr(plhs[0]);
    
    *status = (double ) _main( (UINT32 ) m, eladdr, msg );

    mxFree( addr );
    mxFree( msg );

    return;
}
